package io.gitee.welson.sensitive.config;

import io.gitee.welson.sensitive.annotation.EnableSensitiveExportStrategy;
import io.gitee.welson.sensitive.annotation.SensitiveStrategyComponent;
import io.gitee.welson.sensitive.strategy.SensitiveStrategy;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author welson
 */
public class SensitiveStrategyRegistrar implements ImportBeanDefinitionRegistrar {

    /**
     * starter内置策略包路径
     */
    private static final String BUILT_IN_STRATEGY_PACKAGE = "io.gitee.welson.sensitive.strategy.impl";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        Set<String> basePackages = new LinkedHashSet<>();

        // 1. 添加starter内置策略包路径
        basePackages.add(BUILT_IN_STRATEGY_PACKAGE);

        // 2. 获取@EnableSensitiveStrategy注解的配置
        AnnotationAttributes attributes = AnnotationAttributes
                .fromMap(metadata.getAnnotationAttributes(EnableSensitiveExportStrategy.class.getName()));

        if (attributes != null) {
            // 添加用户配置的包路径
            String[] configuredPackages = attributes.getStringArray("basePackages");
            if (configuredPackages.length > 0) {
                Collections.addAll(basePackages, configuredPackages);
            } else {
                // 如果用户没有指定包路径，使用启动类所在的包路径
                basePackages.add(ClassUtils.getPackageName(metadata.getClassName()));
            }
        }

        // 创建扫描器并配置过滤器
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(SensitiveStrategyComponent.class));
        scanner.addIncludeFilter(new AssignableTypeFilter(SensitiveStrategy.class));

        // 执行扫描
        scanner.scan(StringUtils.toStringArray(basePackages));
    }
}